/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package ejercicio.practica9;

import java.util.Random;

/**
 *
 * @author manolo
 */
public class monitorImpresion implements Runnable {

    volatile static int numImpresoras = 3;

    public void solicitaImpresora() throws InterruptedException {

        synchronized (this) {
            while (numImpresoras == 0) {
                System.out.println("Las impresoras están ocupadas");
                wait();
            }            
            numImpresoras--;
            System.out.println("Se le asigna una impresora para trabajar. Impresoras libres " + numImpresoras);
        }
    }

    public void liberaImpresora() {
        synchronized (this) {
            if (++numImpresoras >= 0) {
                System.out.println("Se ha liberado una impresora");
                notifyAll();
            }
        }
    }

    @Override
    public void run() {
        Random rm = new Random();
        while (true) {
            System.out.println("Se solicita una impresora.");
            try {
                solicitaImpresora();
                Thread.sleep(rm.nextInt(3000));
                liberaImpresora();                
                Thread.sleep(rm.nextInt(1000));
            } catch (InterruptedException ex) {
                System.out.println("Error: " + ex);;
            }

        }
    }
}
